 //
 //  LoginController.swift
 //  TrafficViolation
 //
 //  Created by eaglelive on 2017/4/16.
 //  Copyright © 2017年 eaglelive. All rights reserved.
 //
 
 import Foundation
 import UIKit
 import Alamofire
 import SwiftyJSON
 class LoginController: BaseController {
    let labelW = CGFloat(kScreenW-60)
    let labelX = CGFloat(30)
    let rectImage:CGRect = CGRect(x:0, y:0, width:30, height:40)
    var userName,userPwd:UITextField!//用户名密码
    override func viewDidLoad(){
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        setupNavBar(title: "登录", isback: false, appearWay: 1, isright: false)//自定义导航
        //登录名
        userName = UITextField(frame: CGRect(x:labelX, y:kNavigationBarH + kStatusBarH + 30, width:labelW, height:cellH))
        userName.becomeFirstResponder()//获取焦点
        userName.autocapitalizationType = .none //关闭首字母自动大写
        userName.clearButtonMode=UITextFieldViewMode.whileEditing;
        //设置左边小图片
        let nameLeftView:UIView=UIView(frame: rectImage);
        let leftImage0:UIImageView=UIImageView(frame: CGRect(x:5,y:10, width:15, height:22));
        leftImage0.image=UIImage(named: "user_phone");
        nameLeftView.addSubview(leftImage0)
        userName.leftView = nameLeftView//  设置左边小图片
        userName.leftViewMode = UITextFieldViewMode.always
        userName.placeholder = "请输入手机号/工号"
        userName.text = ""//18772246520
        self.view.addSubview(userName)
        //分割线
        let bseparator1 = UILabel.init(frame: CGRect(x: labelX, y: kNavigationBarH + kStatusBarH + 70, width: labelW, height: 1))
        bseparator1.backgroundColor = separatorColor
        self.view.addSubview(bseparator1)
        //密码
        userPwd = UITextField(frame: CGRect(x:labelX, y:kNavigationBarH + kStatusBarH + 80, width:labelW, height:cellH))
        //设置左边小图片
        let pwdLeftView:UIView=UIView(frame: rectImage);
        let leftImage1:UIImageView=UIImageView(frame: CGRect(x:5,y:10, width:15, height:20));
        leftImage1.image=UIImage(named: "password");
        pwdLeftView.addSubview(leftImage1)
        userPwd.leftView = pwdLeftView//  设置左边小图片
        userPwd.leftViewMode = UITextFieldViewMode.always
        userPwd.autocapitalizationType = .none //关闭首字母自动大写
        userPwd.isSecureTextEntry = true
        userPwd.placeholder = "请输入登录密码"
        userPwd.text = ""//12345687
        self.view.addSubview(userPwd)
        //分割线
        let bseparator2 = UILabel.init(frame: CGRect(x: labelX, y: kNavigationBarH + kStatusBarH + 120, width: labelW, height: 1))
        bseparator2.backgroundColor = separatorColor
        self.view.addSubview(bseparator2)
        //登陆按钮
        let button:UIButton = UIButton(type:.custom)
        button.frame = CGRect(x:labelX, y:kNavigationBarH + kStatusBarH + 140, width:labelW, height:cellH)//设置登陆按钮位置和大小
        button.layer.cornerRadius = 10;
        button.backgroundColor = appMainColor
        button.showsTouchWhenHighlighted = true //
        button.adjustsImageWhenHighlighted=false ////使触摸模式下按钮也不会变暗（半透明
        button.setTitle("登录", for:.normal)
        button.addTarget(self, action: #selector(loginBtnClick), for: UIControlEvents.touchUpInside)
        self.view.addSubview(button)
        //设置注册按钮
        let buttonRegist:UIButton = UIButton(type:.system)
        buttonRegist.frame = CGRect(x:labelX, y:kNavigationBarH + kStatusBarH + 180, width:70, height:cellH)
        buttonRegist.setTitle("快速注册", for:.normal)
        buttonRegist.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        buttonRegist.addTarget(self, action: #selector(registBtnClick(sender:)), for: UIControlEvents.touchUpInside)
        self.view.addSubview(buttonRegist)
        //忘记密码
        let buttonForget:UIButton = UIButton(type:.system)
        buttonForget.frame = CGRect(x:kScreenW-100, y:kNavigationBarH + kStatusBarH + 180, width:70, height:cellH)
        buttonForget.setTitle("忘记密码?", for:.normal)
        buttonForget.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        buttonForget.addTarget(self, action: #selector(forgotPWDClick(sender:)), for: UIControlEvents.touchUpInside)
        self.view.addSubview(buttonForget)
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
}
 extension LoginController{
    //注册点击事件
    func registBtnClick(sender: UIButton) {
        let mainVC = UINavigationController(rootViewController: RegistController())
        app.window?.rootViewController = mainVC
    }
    //找回密码点击事件
    func forgotPWDClick(sender: UIButton) {
        let mainVC = UINavigationController(rootViewController: ForgotPWDViewController())
        app.window?.rootViewController = mainVC
    }
    //登陆按钮
    func loginBtnClick(){
        if "" == userName.text! || "" == userPwd.text! {
            checkAlertFun(message: "登录名和密码不能为空！")
        }else{
            loginInFunc()
        }
    }
    //登录
    func loginInFunc(){
        if reachability.isReachable{
            //登陆帐号密码
            let parameter:[String:Any] = [
                "loginID":userName.text!,
                "password":userPwd.text!
            ]
            Alamofire.request("\(projectUrl)/user/login",method:.post, parameters:parameter,headers:headers).responseJSON { (response) in
                let jsonString = response.result.value!
                let jsonDate = JSON(jsonString)
                if jsonDate["success"] == true {
                    userDefault.set(jsonDate["rdata"]["userID"].rawString()!, forKey: "userID")
                    userDefault.set(jsonDate["rcode"].rawValue as! String, forKey: "tokenID")
                    userDefault.set(jsonDate["rdata"]["userType"].rawString()!, forKey: "isEmployee")
                    //登录成功后把用户基本信息插入数据库
                    let model:JSON = jsonDate["rdata"]
                    let personalModel : PersonalModel = PersonalModel.init(dict: model, tokenID: jsonDate["rcode"].rawValue as! String)
                    if personalModel.insertOrUpdatePersonalToDB() {
                        userID = userDefault.object(forKey: "userID")//用户ID
                        tokenID = userDefault.object(forKey: "tokenID")//登录标识
                        isEmployee = userDefault.object(forKey: "isEmployee") as! String
                        let mainVC = UINavigationController(rootViewController: MainViewController())
                        app.window?.rootViewController = mainVC
                        NSLog("用户登录信息插入数据成功！")
                    }else{
                        NSLog("用户登录信息插入数据失败！")
                    }
                }else{
                    let alertController = UIAlertController(title: alertTitle, message: jsonDate["rdata"].rawString(), preferredStyle: .alert)
                    let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
                    alertController.addAction(cancelAction)
                    self.present(alertController, animated: true, completion: nil)
                }
            }
        }else{
            let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
}
